package com.linxi.wordslog.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.navigation.Navigation
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.linxi.wordslog.R
import com.linxi.wordslog.WordApplication
import com.linxi.wordslog.data.Result
import com.linxi.wordslog.data.room.Word
import com.linxi.wordslog.wordslogviewmodel.AddWordViewModel
import com.linxi.wordslog.wordslogviewmodel.WordViewModel


class AddAdapter(private val wordViewModel: WordViewModel) :ListAdapter<Result, AddViewHolder>(
    object :DiffUtil.ItemCallback<Result>() {
        override fun areItemsTheSame(oldItem: Result, newItem: Result): Boolean {
            return newItem == oldItem
        }

        override fun areContentsTheSame(
            oldItem: Result,
            newItem: Result
        ): Boolean {
            return oldItem.src == newItem.src
        }

    }
) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cell_add_words, parent, false)
        val holder = AddViewHolder(view)
        holder.itemView.setOnClickListener {
            (WordApplication.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                .hideSoftInputFromWindow(it.windowToken, 0)
            val position = holder.adapterPosition
            val english =getItem(position).src
            val chineseMeaning = getItem(position).tgt
            val word = Word(word = english, chineseMeaning = chineseMeaning)
            wordViewModel.insertWords(word)
            val controller = Navigation.findNavController(it)
            controller.navigateUp()
        }
        return holder
    }

    override fun onBindViewHolder(holder: AddViewHolder, position: Int) {
        val result = getItem(position)
        holder.apply {
            addEnglish.text = result.src
            addChinese.text = result.tgt
        }
    }

}

class AddViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
    val addEnglish: TextView = itemView.findViewById(R.id.addEnglish)
    val addChinese: TextView = itemView.findViewById(R.id.addChinese)
}